<?php

namespace App\Http\Controllers\Counter;

use App\Cost\CostBuilder;
use App\Enums\CostRuleClassify;
use App\Helper\ApiResponseHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\Counter\CostRuleRequest;
use App\Http\Resources\Counter\CostRuleResource;
use App\Models\CostRule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CostRuleController extends Controller
{
    public function getList(Request $request)
    {
        $classify = CostRuleClassify::from($request->input('classify'));

        $store = Auth::user()->store;

        $costRules = $store->costRules()->where('classify', $classify);

        if ($classify == CostRuleClassify::Table) {
            if (!empty($request->table_type))
                $costRules->where('table_type', $request->input('table_type'));
        } else {
            if (!empty($request->assistant_type_id))
                $costRules->where('assistant_type_id', $request->input('assistant_type_id'));
        }

        return CostRuleResource::collection($costRules->latest()->get());
    }

    public function create(CostRuleRequest $request)
    {
        $name = $request->input('name');
        $data = $request->input('data');
        $type = $request->input('type');

        try {
            $cost = (new CostBuilder())->setType($type)->setData($data)->build();
        } catch (\Exception $exception) {

            return ApiResponseHelper::json([], 400, $exception->getMessage());
        }

        $costRule = new CostRule();
        $costRule->name = $name;
        $costRule->data = $cost;
        $costRule->type = $type;
        $costRule->store_id = Auth::user()->store_id;
        $costRule->classify = $request->input('classify');
        $costRule->table_type = $request->input('table_type');
        $costRule->assistant_type_id = $request->input('assistant_type_id');
        $costRule->save();

        return new CostRuleResource($costRule);
    }

    public function edit(CostRule $costRule, CostRuleRequest $request)
    {
        if ($costRule->store_id != Auth::user()->store_id)
            return ApiResponseHelper::json([], 400, '无权编辑其他店铺的计费规则');

        $name = $request->input('name');
        $data = $request->input('data');
        $type = $request->input('type');

        try {
            $cost = (new CostBuilder())->setType($type)->setData($data)->build();
        } catch (\Exception $exception) {

            return ApiResponseHelper::json([], 400, $exception->getMessage());
        }

        $costRule->name = $name;
        $costRule->data = $cost;
        $costRule->type = $type;
        $costRule->save();

        return new CostRuleResource($costRule);
    }

    public function delete(CostRule $costRule)
    {
        if ($costRule->store_id != Auth::user()->store_id)
            return ApiResponseHelper::json([], 400, '无权删除其他店铺的计费规则');

        $costRule->delete();

        return ApiResponseHelper::json([]);
    }
}
